﻿using System;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Threading.Tasks;
using ArchivesAdmin.Util;
using ArchivesAdmin.Util.Extension;
using ArchivesAdmin.Util.Model;
using ArchivesAdmin.Data;
using ArchivesAdmin.Data.Repository;
using ArchivesAdmin.Entity.StorageManage;
using ArchivesAdmin.Model.Param.StorageManage;
using ArchivesAdmin.Web.Code;
using ArchivesAdmin.Model.Result.StorageManage;

namespace ArchivesAdmin.Service.StorageManage
{
    /// <summary>
    /// 创 建：admin
    /// 日 期：2021-06-19 09:36
    /// 描 述：服务类
    /// </summary>
    public class BarLibService : RepositoryFactory
    {
        string startid = "";
        string childId;
        #region 私有方法
        private List<DbParameter> ListFilterForLatestBoxBinCodes(string arctype, int arcyear, string boxorbin, StringBuilder strSql, string frompage)
        {
            Task<OperatorInfo> user = Operator.Instance.Current();

            long curUserId = 0;
            if (user != null)
            {
                curUserId = (long)user.Result.UserId;
            }
            else
            {
                curUserId = 0;
            }

            strSql.Append(@"SELECT  id as Id,
                                    base_create_time as BaseCreateTime,
                                    base_creator_id as BaseCreatorId,
                                    archiveid as ArchiveId,
                                    category as Category,
                                    boxcode as BoxCode,
                                    bincode as BinCode,
                                    binsecret as BinSecret,
                                    sortnum as SortNum,
                                    isprinted as IsPrinted
                            FROM    barlib                                    
                            WHERE   1 = 1  ");

            var parameter = new List<DbParameter>();
            if (!string.IsNullOrEmpty(arctype))
            {
                strSql.Append(" AND arctype = @ArcType");
                parameter.Add(DbParameterExtension.CreateDbParameter("@ArcType", arctype));
            }
            if (arcyear != 0)
            {
                strSql.Append(" AND arcyear = @ArcYear");
                parameter.Add(DbParameterExtension.CreateDbParameter("@ArcYear", arcyear));
            }

            if (!string.IsNullOrEmpty(boxorbin))
            {
                strSql.Append(" AND category = @Category");
                parameter.Add(DbParameterExtension.CreateDbParameter("@Category", boxorbin));
            }

            if (curUserId != 0)
            {
                strSql.Append(" AND base_creator_id = @CreatorId");
                parameter.Add(DbParameterExtension.CreateDbParameter("@CreatorId", curUserId));
            }
            if (frompage == "BarLib" && boxorbin == "BIN") strSql.Append(" and  tempbincode = '-' ");

            strSql.Append(" order by base_create_time desc  limit 1");  // 只查当前用户最新的一条记录
            return parameter;
        }

        private List<DbParameter> ListFilterForBoxCodesNotMapped(string arctype, int arcyear, string boxorbin, StringBuilder strSql, string frompage)
        {
            Task<OperatorInfo> user = Operator.Instance.Current();

            long curUserId = 0;
            if (user != null)
            {
                curUserId = (long)user.Result.UserId;
            }
            else
            {
                curUserId = 0;
            }

            strSql.Append(@"SELECT  id as Id,
                            base_is_delete as BaseIsDelete,                            
                                    base_create_time as BaseCreateTime,
                                    base_modify_time as BaseModifyTime,
                                    base_creator_id as BaseCreatorId,                                    
                                    base_modifier_id as BaseModifierId,
                                    base_version as BaseVersion,
                                    archiveid as ArchiveId,
                                    arctype as ArcType,
                                    arcyear as ArcYear,
                                    category as Category,
                                    boxcode as BoxCode,
                                    bincode as BinCode,
                                    binsecret as BinSecret,
                                    sortnum as SortNum,
                                    isprinted as IsPrinted
                            FROM    barlib                                    
                            WHERE   1 = 1  AND category = 'BOX' ");

            var parameter = new List<DbParameter>();
            if (!string.IsNullOrEmpty(arctype))
            {
                strSql.Append(" AND arctype = @ArcType");
                parameter.Add(DbParameterExtension.CreateDbParameter("@ArcType", arctype));
            }
            if (arcyear != 0)
            {
                strSql.Append(" AND arcyear = @ArcYear");
                parameter.Add(DbParameterExtension.CreateDbParameter("@ArcYear", arcyear));
            }

            if (curUserId != 0)
            {
                strSql.Append(" AND base_creator_id = @CreatorId");
                parameter.Add(DbParameterExtension.CreateDbParameter("@CreatorId", curUserId));
            }

            if (frompage == "BarLib")
                strSql.Append(" AND bincode = '' and   tempbincode = '-' ");   // 针对  档案封箱            
            else
                strSql.Append(" AND tempbincode = ''  AND bincode = '-' ");  // 针对  档案周转箱 

            return parameter;
        }

        // 获取需要重打的 箱码、 盒码
        private List<DbParameter> ListFilterForBinBoxCodesReprint(StringBuilder strSql, string frompage)
        {
            Task<OperatorInfo> user = Operator.Instance.Current();

            long curUserId = 0;
            if (user != null)
            {
                curUserId = (long)user.Result.UserId;
            }
            else
            {
                curUserId = 0;
            }

            strSql.Append(@"SELECT  id as Id,
                            base_is_delete as BaseIsDelete,                            
                                    base_create_time as BaseCreateTime,
                                    base_modify_time as BaseModifyTime,
                                    base_creator_id as BaseCreatorId,                                    
                                    base_modifier_id as BaseModifierId,
                                    base_version as BaseVersion,
                                    archiveid as ArchiveId,
                                    arctype as ArcType,
                                    arcyear as ArcYear,
                                    category as Category,
                                    boxcode as BoxCode,
                                    bincode as BinCode,
                                    binsecret as BinSecret,
                                    sortnum as SortNum,
                                    isprinted as IsPrinted,
                                    tempbincode as TempBinCode
                            FROM    barlib                                    
                            WHERE   1 = 1  AND category = 'BIN' ");

            var parameter = new List<DbParameter>();

            if (curUserId != 0)
            {
                strSql.Append(" AND base_creator_id = @CreatorId");
                parameter.Add(DbParameterExtension.CreateDbParameter("@CreatorId", curUserId));
            }

            if (frompage == "BarLib")
                strSql.Append(" AND  tempbincode = '-' ");   // 针对  档案封箱            
            else
                strSql.Append(" AND  bincode = '-' ");  // 针对  档案周转箱 

            strSql.Append(" order by base_create_time desc");

            return parameter;
        }

        #endregion

        #region 获取数据
        public async Task<List<BarLibEntity>> GetLatestBoxBinCodes(string arctype, int arcyear, string boxorbin, string frompage)
        {
            var strSql = new StringBuilder();
            List<DbParameter> filter = ListFilterForLatestBoxBinCodes(arctype, arcyear, boxorbin, strSql, frompage);
            var list = await this.BaseRepository().FindList<BarLibEntity>(strSql.ToString(), filter.ToArray());

            return list.ToList();
        }

        // 获取还没有归类到 箱码 的 盒码 列表
        public async Task<List<BarLibEntity>> GetBoxCodesNotMapped(string arctype, int arcyear, string frompage)
        {
            var strSql = new StringBuilder();
            List<DbParameter> filter = ListFilterForBoxCodesNotMapped(arctype, arcyear, "BOX", strSql, frompage);
            var list = await this.BaseRepository().FindList<BarLibEntity>(strSql.ToString(), filter.ToArray());

            return list.ToList();
        }

        // 获取需要重新打印的  箱码 、 盒码 列表
        public async Task<List<BarLibEntity>> GetReprintCodes(string frompage)
        {
            var strSql = new StringBuilder();
            List<DbParameter> filter = ListFilterForBinBoxCodesReprint(strSql, frompage);
            var list = await this.BaseRepository().FindList<BarLibEntity>(strSql.ToString(), filter.ToArray());

            return list.ToList();
        }

        public async Task<List<BarLibEntity>> GetList(BarLibListParam param)
        {
            var expression = ListFilter(param);
            var list = await this.BaseRepository().FindList(expression);
            return list.ToList();
        }

        public async Task<List<BarLibEntity>> GetPageList(BarLibListParam param, Pagination pagination)
        {
            var expression = ListFilter(param);
            var list = await this.BaseRepository().FindList(expression, pagination);
            return list.ToList();
        }

        public async Task<BarLibEntity> GetEntity(long id)
        {
            return await this.BaseRepository().FindEntity<BarLibEntity>(id);
        }


        //created  by XQ 2021-7-5 (粗糙版，待修改）
        public async Task<string[]> GetArchiveDataByCode(string code)
        {
            StringBuilder s = new StringBuilder();
            List<BarLibEntity> list = new List<BarLibEntity>();
            string allArchivesid = "";

            s.Append(@"select * from barlib");
            var x= await this.BaseRepository().FindList<BarLibEntity>(s.ToString());
            foreach(var y in x)
            {
                list.Add(y);
            }
            foreach(var l in list )
            {
              if(l.Boxcode==code)               
                    allArchivesid += l.Archiveid.ToString()+";";
            }
            string[] data = { allArchivesid, list[0].Isscreenchildid.ToString() };
            return data;

        }

        //created  by XQ 2021-7-5 (粗糙版，待修改）
        public async Task<string> GetArchiveChildIdByArchiveId(string archiveId)
        {
            StringBuilder s = new StringBuilder();
            List<BarLibEntity> list = new List<BarLibEntity>();
            string childId = "";
            s.Append(@"select archiveid,archivechildid from barlib");
            var x = await this.BaseRepository().FindList<BarLibEntity>(s.ToString());
            foreach (var y in x)
            {
                list.Add(y);
            }
            foreach (var l in list)
            {
                if (l!=null)
                {
                    if (l.Archiveid == archiveId && l.Archivechildid != null)
                        childId = l.Archivechildid.ToString();
                }
            }
            return childId;

        }

        #endregion

        #region 提交数据
        public void ReprintCode(string code)
        {   // 重打标签
     //       PrinterHelper.PrintLabel(code);
        }

        public async Task PrintOneBoxCode(BarLibEntity entity, bool isprint,int state)
        {
            // 打印1个盒码：先保存到数据库表中    
            if (state == 0)
                startid = entity.Archiveid;
            childId += entity.Archivechildid + "/";
            try
            {
                if (entity.Id.IsNullOrZero())
                {
                    await entity.Create();
                    await this.BaseRepository().Insert(entity);

                   // 打印标签-- - 盒码
                     if (isprint)
                    {
                        if (entity.Printway == 0)   //为0直接打印
                        {                                                     
                            PrinterHelper.PrintLabel(entity, startid,childId);
                          //  allArchivesId = new StringBuilder();
                            entity.Isprinted = 1;
                        }                     
                    }



                   
                    await this.BaseRepository().Update(entity);
                }
                else
                {
                    await this.BaseRepository().Update(entity);
                }
            }
            catch (Exception e)
            {
                string s = e.Message;
            }
           
        }

        public async Task PrintMultiBoxCodes(List<BarLibEntity> list)
        {   // 打印1-n个盒码：先保存到数据库表中
            foreach (BarLibEntity entity in list)
            {
                if (entity.Id.IsNullOrZero())
                {
                    await entity.Create();
                    await this.BaseRepository().Insert(entity);

                    // 打印标签 --- 盒码
         //          PrinterHelper.PrintLabel(entity.Boxcode);
                    entity.Isprinted = 1;
                    await this.BaseRepository().Update(entity);
                }
                else
                {
                    await this.BaseRepository().Update(entity);
                }
            }

        }
        //public async Task PrintOneChild()


        public async Task PrintBinCode(BarLibEntity entity)
        {   // 针对  档案封箱 
            if (entity.Id.IsNullOrZero())
            {
                await entity.Create();
                await this.BaseRepository().Insert(entity);
                // 将与此员工未入箱的 盒码 记录， bincode 值全部更改为此箱码 
                var list2 = GetBoxCodesNotMapped(entity.Arctype, entity.Arcyear, "BarLib");  // 找 封箱 包含的 盒

                foreach (var ent in list2.Result.ToList())
                {   // BOX记录
                    ent.Bincode = entity.Bincode;
                    await this.BaseRepository().Update(ent);
                }

                // 打印标签 --- 箱码
                PrinterHelper.PrintLabel_Bin(entity);
                entity.Isprinted = 1;
                await this.BaseRepository().Update(entity);
            }
            else
            {
                await this.BaseRepository().Update(entity);
            }
        }

        // 绑定临时周转箱
        public async Task BindTempBinCode(BarLibEntity entity)
        {
            if (entity.Id.IsNullOrZero())
            {
                await entity.Create();
                await this.BaseRepository().Insert(entity);
                // 将与此员工未入箱的 盒码 记录， Tempbincode 值全部更改为此箱码 
                var list2 = GetBoxCodesNotMapped(entity.Arctype, entity.Arcyear, "Circulation");  // 找 周转箱 包含的 盒

                foreach (var ent in list2.Result.ToList())
                {   // BOX记录
                    ent.Tempbincode = entity.Tempbincode;
                    await this.BaseRepository().Update(ent);
                }
                entity.Isfinished = 0;
                await this.BaseRepository().Update(entity);
            }
            else
            {
                await this.BaseRepository().Update(entity);
            }
        }

        public async Task SetBinSecret(BarLibEntity entity)
        {
            if (entity.Id.IsNullOrZero())
            {
                await entity.Create();
                await this.BaseRepository().Insert(entity);
            }
            else
            {
                await this.BaseRepository().Update(entity);
            }
        }
        #endregion

        #region 私有方法
        private Expression<Func<BarLibEntity, bool>> ListFilter(BarLibListParam param)
        {
            var expression = LinqExtensions.True<BarLibEntity>();
            if (param != null)
            {
            }
            return expression;
        }

        private Expression<Func<BarLibEntity, bool>> ListFilter(string code)
        {
            var expression = LinqExtensions.True<BarLibEntity>();
            if (code != null)
            {
            }
            return expression;
        }

        #endregion
    }
}
